import { createRouter, createWebHistory, NavigationFailure, RouteLocation, RouteLocationNormalized } from 'vue-router';
import routes from './route';

/** 声明路由元信息的数据类型 */
declare module 'vue-router' {
	interface RouteMeta {
		/** 图标 */
		icon: string;
		/** 是否缓存 */
		keepAlive: boolean;
		/** 中文名称 */
		zhName: string;
		/** 是否需要权限校验 */
		requiresAuth: boolean;
	}
}

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: routes,
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition;
		} else {
			return { top: 0 };
		}
	},
});

export default router;

/**
 * 前置守卫
 * @params { RouteLocation } to 即将要进入的目标路由
 * @params { RouteLocation } from 正要离开的路由
 * @returns {Boolean | String | Object} 是否放行
 */
router.beforeEach(async (to: RouteLocation, from: RouteLocation) => {
	console.log(to, from);

	return true;
});

/**
 * 后置守卫
 * @params { RouteLocationNormalized } to 即将要进入的目标路由
 * @params { RouteLocationNormalized } from 正要离开的路由
 * @params { NavigationFailure } failure 导航失败的额外信息
 *
 */
router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized, failure?: NavigationFailure) => {
	console.log(to, from, failure);
});
